package btb.engine;

public abstract class ATask extends Thread
{
	public static final int UNINITIALIZED	= -1;
	public static final int INITIALIZED		= 0;
	
	protected boolean die = false;
	protected boolean childTask = false;
	protected ATask parentTask = null;
	protected int taskId = UNINITIALIZED;
	protected CTaskMessenger mailbox = null;
	protected CEvent newEvent = null;
	
	public ATask(int _taskId)
	{
		this.taskId = _taskId;
		this.initialize();
	}
	
	public ATask(ATask _parentTask, int _taskId)
	{
		this.parentTask = _parentTask;
		this.taskId = _taskId;
		
		if(this.parentTask != null)
			this.childTask = true;
		
		this.initialize();
	}
	
	public ATask(int _taskId, CTaskMessenger _mailbox)
	{
		this.taskId = _taskId;
		this.mailbox = _mailbox;
		this.initialize();
	}
	
	public ATask(ATask _parentTask, int _taskId, CTaskMessenger _mailbox)
	{
		this.parentTask = _parentTask;
		this.taskId = _taskId;
		this.mailbox = _mailbox;
		
		if(this.parentTask != null)
			this.childTask = true;
		
		this.initialize();
	}
	
	public void initialize(){}
	
	public void run()
	{
		while(!this.die)
		{
			this.update();
		}
		
		// [Refactoring]: Any code to stop actual thread that task is running within, cleanup procedures, etc should go here.
	}
	
	public abstract void update();
	public abstract void handleEvent(CEvent _event);
	public abstract void handleDeath();
	
	public void handleMail()
	{
		if(this.getMailbox() != null)
		{
			while((this.newEvent = this.getMailbox().pull(this.taskId)) != null )
			{
				this.handleEvent(this.newEvent);
			}
		}
	}
	
	public synchronized void kill()
	{
		handleDeath();
		this.die = true;
	}
	
	public boolean isChild() {
		return this.childTask;
	}
	
	public CTaskMessenger getMailbox()
	{
		return this.mailbox;
	}
	
	public ATask getParentTask() {
		return this.parentTask;
	}
	
	public int getTaskId() {
		return this.taskId;
	}
}
